﻿using DeviceAlarmService.Models;
using System.Collections;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Json;

namespace DeviceAlarmService.SystemService;

public static class ConfigService
{
    public static SystemConfiguration Configuration { get; private set; }

    public static void GetSettings()
    {
        string str = GetGlobalSettings();

        if (str.Length < 1)
        {
            //配置获取失败加载默认数据
            Configuration = new()
            {
                collectionInterval = 2,
                alarmInterval = 600,
                enablePushService = true,
                enableVoiceBroadcastingService = true,
                template = $"设备报警通知\t\n设备：name\t\n级别：level\t\n时间：date\t\n信息：information\t\n",
                passageway = Models.Message.MessageEnum.NULL
            };
        }
        else
        {
            Configuration = JsonSerializer.Deserialize<SystemConfiguration>(str);
        }
    }


    /// <summary>
    /// 获取全局配置文件
    /// </summary>
    /// <returns></returns>
    public static string GetGlobalSettings()
    {
        if (File.Exists("Settings.json"))
        {
            return File.ReadAllText("Settings.json");
        }
        return "";
    }

    /// <summary>
    /// 获取设备ID
    /// </summary>
    /// <returns></returns>
    public static ArrayList GetID()
    {
        try
        {
            ArrayList arrayList = new();

            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly()!.Location!)!, "json");

            string[] txtFiles = Directory.GetFiles(path, "*.json");

            foreach (var item in txtFiles)
            {
                arrayList.Add(Path.GetFileName(item).Replace(".json", ""));
            }
            return arrayList;
        }
        catch (Exception)
        {

            return null;
        }

    }

    public static void WriteConfiguration(SystemConfiguration Configuration)
    {

        string jsonString = JsonSerializer.Serialize(Configuration, new JsonSerializerOptions()
        {
            Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
        });

        File.WriteAllText("Settings.json", jsonString);
    }
}